package com.bb.blog.web.exception;

import com.bb.blog.web.component.ResponseUtil;
import com.bb.blog.web.model.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.bind.MethodArgumentNotValidException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(value = ServerException.class)
    public CommonResponse handleServerException(ServerException ex) {
        log.error("出现ServerException ------------------------->", ex);
        return ResponseUtil.fail(ex.getCode(), ex.getMsg(), ex.getData());
    }

    @ExceptionHandler(value = RuntimeException.class)
    public CommonResponse handleRuntimeException(RuntimeException ex) {
        log.error("出现 RuntimeException -------------------->", ex);
        return ResponseUtil.fail(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResponse<Object> handleMethodArgumentNotValidException(
            MethodArgumentNotValidException methodArgumentNotValidException
    ) {
        StringBuilder sb = new StringBuilder();
        if (methodArgumentNotValidException.getBindingResult().hasErrors()) {
            methodArgumentNotValidException.getBindingResult().getAllErrors().forEach(e->{
                sb.append(e.getDefaultMessage()).append(",");
                log.error(e.getDefaultMessage());
            });
        }
        sb.deleteCharAt(sb.length() -1 );

        return ResponseUtil.fail(400, sb.toString(),null);
    }
//    @ExceptionHandler(value = {})
}
